<script lang="ts" setup>
import type { PosModel } from '#/api/system/models';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm, z } from '#/adapter/form';
import { createPosApi, updatePosApi } from '#/api/system/pos';

defineOptions({
  name: 'PosFormModal',
});

const emit = defineEmits<{
  complete: [];
}>();

async function onSubmit(values: Record<string, any>) {
  const input = values as PosModel;
  await (input.id ? updatePosApi(input) : createPosApi(input));
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      fieldName: 'code',
      dependencies: {
        triggerFields: ['code'],
        disabled(values) {
          return !!values.id;
        },
      },
      label: '职位代码',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'name',
      label: '职位名称',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      defaultValue: 0,
      fieldName: 'order',
      label: '排序',
      rules: z.number().gte(0),
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '禁用',
        class: 'w-auto',
      },
      fieldName: 'status',
      label: '状态',
      defaultValue: 1,
      rules: 'required',
    },
  ],
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (await formApi.validateAndSubmitForm()) {
      modalApi.close();
      emit('complete');
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values } = modalApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values, false);
        modalApi.setState({ title: '编辑职位' });
      }
    }
  },
  title: '新增职位',
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
